import fs from 'fs'
import path from 'path'
import YAML from 'yaml'
import common from '../../lib/common/common.js'

export class XiuXianUtils {
    constructor() {
        // 初始化工具类
    }

    loadJSON(filePath, defaultValue) {
        if (fs.existsSync(filePath)) {
            return JSON.parse(fs.readFileSync(filePath, 'utf8'))
        }
        this.saveJSON(filePath, defaultValue)
        return defaultValue
    }

    saveJSON(filePath, data) {
        fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf8')
    }

    loadYAML(filePath, defaultValue) {
        if (fs.existsSync(filePath)) {
            return YAML.parse(fs.readFileSync(filePath, 'utf8'))
        }
        this.saveYAML(filePath, defaultValue)
        return defaultValue
    }

    saveYAML(filePath, data) {
        fs.writeFileSync(filePath, YAML.stringify(data), 'utf8')
    }

    isOnCD(player, action) {
        const now = Date.now()
        if (player.cd && player.cd[action] && player.cd[action] > now) {
            return true
        }
        return false
    }

    getRemainingCDTime(player, action) {
        const now = Date.now()
        const cdEndTime = player.cd[action]
        return Math.ceil((cdEndTime - now) / 60000)
    }

    setCD(player, action) {
        if (!player.cd) player.cd = {}
        const cdMinutes = this.config.cd[action]
        if (cdMinutes && cdMinutes > 0) {
            player.cd[action] = Date.now() + cdMinutes * 60000
        }
    }

    createNewPlayer() {
        return {
            name: this.generateName(),
            realm: 0,
            level: 1,
            exp: 0,
            energy: 100,
            lingshi: 0,
            hp: 100,
            maxHp: 100,
            attack: 10,
            defense: 5,
            speed: 5,
            critRate: 5,
            critDamage: 150,
            magicAttack: 10,
            magicDefense: 5,
            inventory: { 丹药: [], 灵石: [], 法器: [], 功法: [], 其他: [] },
            cd: {},
            learnedSkills: [],
            skillCooldowns: {},
            lastDailyReward: null
        }
    }

    generateName() {
        const prefix = ['东方', '西门', '南宫', '北冥', '上官', '欧阳', '司马', '诸葛', '长孙', '慕容']
        const suffix = ['晓', '云', '风', '雨', '雪', '霜', '寒', '夏', '春', '秋']
        return prefix[Math.floor(Math.random() * prefix.length)] + suffix[Math.floor(Math.random() * suffix.length)]
    }

    renderPlayerStatusText(player) {
        const inventoryStatus = Object.entries(player.inventory)
            .map(([category, items]) => {
                const itemCounts = items.reduce((acc, item) => {
                    acc[item] = (acc[item] || 0) + 1;
                    return acc;
                }, {});
                const formattedItems = Object.entries(itemCounts)
                    .map(([item, count]) => count > 1 ? `${item}x${count}` : item)
                    .join(', ');
                return `${category}：${formattedItems}`;
            })
            .join('\n');

        const cdStatus = ['修炼', '探索', '战斗'].map(action =>
            `${action}：${this.getCDStatus(player, action)}`
        ).join('\n');

        const avatarUrl = `![图片 #20px #20px](https://q1.qlogo.cn/g?b=qq&s=0&nk=${this.e.user_id})`;
        const learnedSkillsText = player.learnedSkills
            ? player.learnedSkills.map(skillId => this.skills.find(s => s.id === skillId).name).join(', ')
            : '暂无';

        return `${avatarUrl}${player.name}的修仙之旅
***
# 基本属性
\`\`\`
境界：${this.realms[player.realm]}
等级：${player.level}
经验：${player.exp}/${player.level * 100}
灵力：${player.energy}
灵石：${player.lingshi}
生命值：${player.hp}/${player.maxHp}
\`\`\`

# 战斗属性
\`\`\`
攻击力：${player.attack}
防御力：${player.defense}
速度：${player.speed}
暴击率：${player.critRate}%
暴击伤害：${player.critDamage}%
法术攻击：${player.magicAttack}
法术防御：${player.magicDefense}
\`\`\`

# 纳戒
\`\`\`
${inventoryStatus}
\`\`\`

# CD状态
\`\`\`
${cdStatus}
\`\`\`

# 已学习技能
\`\`\`
${learnedSkillsText}
\`\`\``.trim()
    }

    getCDStatus(player, action) {
        if (this.isOnCD(player, action)) {
            return `冷却中（剩余${this.getRemainingCDTime(player, action)}分钟）`
        } else {
            return '可用'
        }
    }

    addItemToInventory(player, item) {
        let category = '其他'
        if (item.includes('丹')) category = '丹药'
        else if (item.includes('灵石')) category = '灵石'
        else if (item.includes('法器')) category = '法器'
        else if (item.includes('功法')) category = '功法'

        player.inventory[category].push(item)
    }

    randomItem() {
        const items = ['小还丹', '大还丹']
        return items[Math.floor(Math.random() * items.length)]
    }

    randomMonster(playerLevel) {
        if (this.monsters.length === 0) {
            return this.createDefaultMonster(playerLevel)
        }

        const availableMonsters = this.monsters.filter(m => Math.abs(m.level - playerLevel) <= 5)
        if (availableMonsters.length === 0) {
            return this.createDefaultMonster(playerLevel)
        }

        const monster = availableMonsters[Math.floor(Math.random() * availableMonsters.length)]

        return {
            ...monster,
            hp: monster.level * 20,
            maxHp: monster.level * 20,
            attack: monster.level * 5,
            defense: monster.level * 2,
            speed: monster.level * 1,
            critRate: 5,
            critDamage: 150,
            magicAttack: monster.level * 5,
            magicDefense: monster.level * 2
        }
    }

    createDefaultMonster(playerLevel) {
        const level = Math.max(1, playerLevel - 2 + Math.floor(Math.random() * 5))
        return {
            name: `等级${level}的野怪`,
            level: level,
            hp: level * 20,
            maxHp: level * 20,
            attack: level * 5,
            defense: level * 2,
            speed: level * 1,
            critRate: 5,
            critDamage: 150,
            magicAttack: level * 5,
            magicDefense: level * 2
        }
    }

    calculateDamage(attacker, defender) {
        let damage = attacker.attack - defender.defense

        if (Math.random() * 100 < attacker.critRate) {
            damage *= attacker.critDamage / 100
            damage = Math.floor(damage)
        }

        damage += Math.floor(Math.random() * 5) - 2

        return Math.max(1, damage)
    }

    updatePlayerState(player) {
        if (player.exp >= player.level * 100) {
            player.level++
            player.exp = 0
        }

        if (player.energy <= 0) {
            player.energy = 100
        }

        player.hp = Math.min(player.hp, player.maxHp)
    }

    updateTaskProgress(player, actionType) {
        if (!player.taskProgress) player.taskProgress = {}
        this.tasks.forEach(task => {
            if (task.type === actionType) {
                player.taskProgress[task.id] = (player.taskProgress[task.id] || 0) + 1
            }
        })
    }

    generateRandomTask() {
        const taskTypes = ['修炼', '探索', '战斗', '突破', '使用丹药', '购买法器']
        const type = taskTypes[Math.floor(Math.random() * taskTypes.length)]
        const requirement = Math.floor(Math.random() * 10) + 1
        const reward = {
            exp: Math.floor(Math.random() * 100) + 50,
            lingshi: Math.floor(Math.random() * 50) + 25
        }

        return {
            id: Date.now(),
            name: `${type}大师`,
            description: `完成${requirement}次${type}`,
            requirement,
            type,
            reward
        }
    }

    updateSectAttributes(sect) {
        sect.maxMembers = 10 + (sect.level - 1) * 5
        sect.cultivationBonus = sect.level * 0.05
        sect.resourceLimit = 10000 + (sect.level - 1) * 5000
    }

    getSectUpgradeInfo(level) {
        let info = '升级奖励：\n'
        info += `- 成员上限增加到 ${10 + (level - 1) * 5} 人\n`
        info += `- 宗门修炼加成提升到 ${level * 5}%\n`
        info += `- 资源上限提升到 ${10000 + (level - 1) * 5000}\n`

        if (level % 5 === 0) {
            info += '- 解锁新的宗门技能（待实现）\n'
        }

        return info
    }

    calculateCombatPower(player) {
        return player.attack + player.defense + player.speed +
            player.magicAttack + player.magicDefense +
            (player.realm * 100) + (player.level * 10);
    }

    async markdown(e, msg, desc = '', msgsscr = false) {
        return await common.makeForwardMsg(e, [{
            type: 'node',
            message: {
                type: 'markdown',
                content: msg
            }
        }], desc, msgsscr)
    }
}
